package com.rzcoding.service;

import com.rzcoding.client.BankBClient;
import com.rzcoding.dao.AccountMapper;
import com.rzcoding.entity.Account;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountService {

    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private BankBClient bankBClient;

    @GlobalTransactional
    @Transactional
    public void updAmount(String mode)  {
        Account account = accountMapper.selectByPrimaryKey("1");

        if ("IN".equalsIgnoreCase(mode)) {
            account.setAccount_balance(account.getAccount_balance() + 100);
            // 通过Feign向B银行服务转账
            bankBClient.updAmount("OUT");
        } else if ("OUT".equalsIgnoreCase(mode)){
            account.setAccount_balance(account.getAccount_balance() - 100);
            // 通过Feign向B银行服务转账
            bankBClient.updAmount("IN");
            /**
             *   B 已经提交事务了，B +100块 1100
             *   A 在sleep，事务未提交   依然为1000
             *   A 异常，回滚，1000   B回滚 1000
             *   2PC事务解决！
             */
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String a = null;
            a.length();
        }
        accountMapper.updateByPrimaryKeySelective(account);

        if ("error".equalsIgnoreCase(mode)) {
            bankBClient.updAmount("error");
        }
    }
}
